package db

import (
	"database/sql"
	_ "github.com/go-sql-driver/mysql"
	"go-log/config"
	"log"
)

var TaosDb *sql.DB
var dbErr error

var sqlStr = `
	CREATE TABLE IF NOT EXISTS go_logs.logs
	(
	    -- KEY列
	 	ts DATETIME(3) NOT NULL COMMENT "日志时间",
		app_name VARCHAR(30) NOT NULL COMMENT "应用名称",
		node_id VARCHAR(10) NOT NULL COMMENT "节点名称",
		file_row_number int NOT NULL COMMENT "文件行号",
	    -- VALUE列
		level VARCHAR(10) NOT NULL COMMENT "日志级别",
		trace_id VARCHAR(100) NOT NULL COMMENT "traceId",
		thread_name VARCHAR(200) NOT NULL COMMENT "线程名称",
		class_name VARCHAR(200) NOT NULL COMMENT "类名",
		line_number int NOT NULL COMMENT "行号",
		context STRING COMMENT "日志内容",
		INDEX idx_context(context) USING INVERTED PROPERTIES("parser" = "unicode", "support_phrase" = "true")
	)
	-- 数据表模型 DUPLICATE模型
	DUPLICATE KEY(ts, app_name, node_id, file_row_number)
	PARTITION BY RANGE (ts) ()
	DISTRIBUTED BY HASH(app_name) BUCKETS 32
	PROPERTIES
	(
	"replication_num" = "1",
	"dynamic_partition.time_unit" = "DAY",
	"dynamic_partition.start" = "-30",
	"dynamic_partition.end" = "1",
	"dynamic_partition.prefix" = "p",
	"dynamic_partition.buckets" = "32",
	"dynamic_partition.replication_num" = "1"
	)
`

func init() {
	dsn := config.Conf.TdDsn
	TaosDb, dbErr = sql.Open("mysql", dsn)
	if dbErr != nil {
		log.Fatalf("Error Open : %v, %v", dsn, dbErr)
	}
	dbErr = TaosDb.Ping()
	if dbErr != nil {
		log.Fatalf("Error Ping : %v, %v", dsn, dbErr)
	}
	_, dbErr = TaosDb.Exec("CREATE DATABASE IF NOT EXISTS `go_logs`")
	if dbErr != nil {
		log.Fatalf("Error CREATE DATABASE : %v, %v", dsn, dbErr)
	}
	_, dbErr = TaosDb.Exec(sqlStr)
	if dbErr != nil {
		log.Fatalf("Error CREATE STABLE : %v, %v", dsn, dbErr)
	}
	log.Printf("connectd [%v]\n", dsn)
}
